#!/bin/bash

LOG_DIR=$HADOOP_HOME/logs

# 检查进程是否运行正常，参数1为进程名$1， 参数2为进程端口$2
function check_process(){
	## 根据进程名$1获取进程号	-v 反选 -i 忽略大小写
 	pid=$(ps -ef 2>/dev/null | grep -v grep | grep -i $1 | awk '{print $2}')
	## 根据端口号$2获取进程号
	ppid=$(netstat -ntlp 2>/dev/null |grep $2 | awk '{print $7}' | cut -d '/' -f 1)
	## 输出pid
	echo $pid
	## 相等且不为空则正常返回0
	[[ "$pid" =~ "$ppid" ]] && [ "$ppid" ] && return 0 || return 1
}

function start_process(){
	# 获取进程id
	datanode_pid=$(check_process JobHistoryServer 10020)
	# 待执行的命令 执行的是定义好的脚本 不必重定向输出
	# cmd="start-yarn.sh > $YARN_LOG_DIR/yarn.log 2>&1 "	
	cmd="mapred --daemon start historyserver > $LOG_DIR/JobHistoryServer.log 2>&1"	
	[ -z "${datanode_pid}" ] && eval $cmd || echo "JobHistoryServer服务已启动"
}

function stop_process(){
        datanode_pid=$(check_process JobHistoryServer 10020)
	cmd="mapred --daemon stop historyserver"
        [ "${datanode_pid}" ] && eval $cmd || echo "JobHistoryServer服务未启动"
}
function status_process(){
	check_process JobHistoryServer 10020 >/dev/null && echo "JobHistoryServer服务运行正常" || echo "JobHistoryServer服务运行异常"
}

case $1 in
	"start")
		start_process
		;;
	"stop")
		stop_process
		;;
	"status")
		status_process
		;;
	"restart")
		stop_process
		sleep 2
		start_process
		;;
	*)
		echo "Invalid Args!"
		echo 'Usage: '$(basename $0)' start|stop|status|restart'
		;;

esac
